package com.yyw.gulimall.cart.controller;

import com.yyw.common.constant.common.UrlConstant;
import com.yyw.common.utils.R;
import com.yyw.gulimall.cart.service.CartService;
import com.yyw.gulimall.cart.vo.CartItemVo;
import com.yyw.gulimall.cart.vo.CartVo;
import com.yyw.gulimall.cart.vo.CheckCartVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @Classname CartController
 * @Description 购物车控制器
 * @Date 2020/12/21 13:45
 * @Created yyw
 */
@Controller
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CartController {

    private final CartService cartService;


    /**
     * 查看购物车
     *
     * @return
     */
    @GetMapping("/list")
    public String list(Model model) {
        CartVo vo = cartService.getCartList();
        model.addAttribute("result", vo);
        return "cartList";
    }

    /**
     * 添加商品到购物车
     *
     * @param skuId
     * @param num
     * @return
     */
    @GetMapping("/addCart/{skuId}/{num}")
    public String addCart(@PathVariable("skuId") String skuId, @PathVariable("num") String num,
                          RedirectAttributes redirectAttributes) {
        cartService.addShoppingCart(skuId, num);
        redirectAttributes.addAttribute("skuId", skuId);
        return "redirect:" + UrlConstant.CART_URL + "/cartSuccess";
    }

    /**
     * 添加商品成功后跳转成功页
     * 防止表单重复提交
     *
     * @param skuId
     * @param model
     * @return
     */
    @GetMapping("/cartSuccess")
    public String success(@RequestParam("skuId") String skuId, Model model) {
        CartItemVo vo = cartService.getCartBySkuId(skuId);
        model.addAttribute("result", vo);
        return "success";
    }

    /**
     * 购物车列表，修改购物项的属性
     * @param cartVo
     * @return
     */
    @PostMapping("/checkCart")
    @ResponseBody
    public R checkCart(@RequestBody CheckCartVo cartVo) {
        try {
            cartService.updateCart(cartVo);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 购物车列表，删除购物车
     * @param skuid
     * @param model
     * @return
     */
    @GetMapping("/delCartItem")
    public String delItem(@RequestParam String skuid, Model model) {
        cartService.delItem(skuid);
        return "redirect:" + UrlConstant.CART_URL + "/list";
    }
}
